package org.zhangsh.netty.echo;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.zhangsh.socket.HostInfo;

/**
 * </p>
 *
 * @author zhangsh
 * @version 1.0.0
 * @since 2019-04-27
 */
public class EchoClientHandler extends SimpleChannelInboundHandler<String> {

    private int counter = 0;
    private static final String REQUEST = "zhangshuhui$_";

    public EchoClientHandler(){

    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端remove");
        super.handlerRemoved(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        System.out.println(HostInfo.THREAD_NAME + "开始发送数据");

        for(int i=0; i<10; i++){
            Thread.sleep(2000L);
            ctx.writeAndFlush(Unpooled.copiedBuffer(REQUEST.getBytes()));
        }

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println(HostInfo.THREAD_NAME + "服务器响应 [" + msg + "]the counter : " + ++counter);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

        System.out.println(HostInfo.THREAD_NAME + "接收完成");
        super.channelReadComplete(ctx);
    }
}
